package com.example.weight.captcha;

import android.animation.Animator;
import android.content.Context;
import android.content.res.TypedArray;
import android.support.annotation.AttrRes;
import android.support.annotation.IntDef;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.example.weight.R;

/**
 * Created by judge on 2018/1/17.
 */

public class Captcha extends LinearLayout {

    //控件成员
    private PictureVerifyView verifyView;         //拼图块
    private PicSeekBar seekBar;                    //滑动条块
    private View accessSuccess, accessFailed;       //验证成功/失败显示的视图
    private TextView accessText, accessFailedText;  //验证成功/失败显示的文字

    private int maxFailedCount;      //最大失败次数
    private int failCount;           //已失败次数
    private int oldSign;
    //处理滑动条逻辑
    private boolean isResponse;
    private boolean isDown;

    private CaptchaListener mListener;

    /**
     * 带滑动条验证模式
     */
    public static final int MODE_BAR = 1;
    /**
     * 不带滑动条验证，手触模式
     */
    public static final int MODE_NONBAR = 2;

    @IntDef(value = {MODE_BAR, MODE_NONBAR})
    public @interface Mode {
    }

    public interface CaptchaListener {

        /**
         * Called when captcha success.
         *
         * @param time cost of success time
         * @return text to show,show default when return null
         */
        String onSuccess(long time, String vHash, String vCode);

        /**
         * Called when captcha failed.
         *
         * @param failCount fail count
         * @return text to show,show default when return null
         */
        String onFailed(int failCount);

        /**
         * Called when captcha failed
         *
         * @return text to show,show default when return null
         */
        String onMaxFailed();

    }


    public Captcha(@NonNull Context context) {
        super(context);
    }

    public Captcha(@NonNull Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public Captcha(@NonNull final Context context, @Nullable AttributeSet attrs, @AttrRes int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.Captcha);
        maxFailedCount = typedArray.getInteger(R.styleable.Captcha_max_fail_count, 3);
        typedArray.recycle();
        init();
    }


    private void init() {
        View parentView = LayoutInflater.from(getContext()).inflate(R.layout.container, this, true);
        verifyView = parentView.findViewById(R.id.verifyView);
        seekBar = parentView.findViewById(R.id.seek_bar);
        accessSuccess = parentView.findViewById(R.id.accessRight);
        accessFailed = parentView.findViewById(R.id.accessFailed);
        accessText = parentView.findViewById(R.id.accessText);
        accessFailedText = parentView.findViewById(R.id.accessFailedText);
        verifyView.callback(new PictureVerifyView.Callback() {
            @Override
            public void onSuccess(long time, String vHash, String vCode) {
                if (mListener != null) {
                    String s = mListener.onSuccess(time, vHash, vCode);
                    if (s != null) {
                        accessText.setText(s);
                    } else {//默认文案
                        accessText.setText(String.format(getResources().getString(R.string.verify_access), time));
                    }
                }
                accessSuccess.setVisibility(VISIBLE);
                accessFailed.setVisibility(GONE);
            }

            @Override
            public void onFailed() {
                seekBar.setProgress(0);
                verifyView.reset();
                oldSign = 0;
//                failCount = failCount > maxFailedCount ? maxFailedCount : failCount + 1;
                failCount = 0;
                accessFailed.setVisibility(VISIBLE);
                accessSuccess.setVisibility(GONE);
                if (mListener != null) {
                    if (failCount == maxFailedCount) {
                        String s = mListener.onMaxFailed();
                        if (s != null) {
                            accessFailedText.setText(s);
                        } else {//默认文案
                            accessFailedText.setText(getResources().getString(R.string.verify_failed));
                        }
                    } else {
                        String s = mListener.onFailed(failCount);
                        if (s != null) {
                            accessFailedText.setText(s);
                        } else {//默认文案
                            accessFailedText.setText(getResources().getString(R.string.verify_failed));
                        }
                    }
                }
            }

        });

        //用于处理滑动条渐滑逻辑
        seekBar.setOnSeekBarChangeListener(new PicSeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(PicSeekBar seekBar, int progress, boolean fromUser) {
                if(fromUser) {
                    isResponse = true;
                    verifyView.move(progress);
                }else {
                    isResponse = false;
                }
            }

            @Override
            public void onStartTrackingTouch(PicSeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(PicSeekBar seekBar) {
                if(isResponse) {
                    verifyView.loose(seekBar.getProgress());
                }
            }
        });
    }


    private void startRefresh(View v) {
        //点击刷新按钮，启动动画
        v.animate().rotationBy(360).setDuration(500)
                .setInterpolator(new AccelerateDecelerateInterpolator())
                .setListener(new Animator.AnimatorListener() {
                    @Override
                    public void onAnimationStart(Animator animation) {

                    }

                    @Override
                    public void onAnimationEnd(Animator animation) {
                        reset(false);
                    }

                    @Override
                    public void onAnimationCancel(Animator animation) {

                    }

                    @Override
                    public void onAnimationRepeat(Animator animation) {

                    }
                });
    }


    public void setCaptchaListener(CaptchaListener listener) {
        this.mListener = listener;
    }

    public void setMaxFailedCount(int count) {
        this.maxFailedCount = count;
    }

    public int getMaxFailedCount() {
        return this.maxFailedCount;
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
    }

    /**
     * 复位
     *
     * @param clearFailed 是否清除失败次数
     */
    public void reset(boolean clearFailed) {
        hideText();
        verifyView.reset();
        seekBar.setProgress(0);
        if (clearFailed) {
            failCount = 0;
        } else {
            verifyView.setTouchEnable(true);
        }
    }

    /**
     * 隐藏成功失败文字显示
     */
    public void hideText() {
        accessFailed.setVisibility(GONE);
        accessSuccess.setVisibility(GONE);
    }
}
